package com.furtherstar.auth.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.furtherstar.auth.controller.dto.AuthorizationApply;
import com.furtherstar.auth.controller.dto.AuthorizedResources;
import com.furtherstar.auth.controller.dto.PasswordChangeApply;
import com.furtherstar.auth.controller.dto.UserCredential;
import com.furtherstar.auth.dao.model.App;
import com.furtherstar.auth.dao.model.CorpWork;
import com.furtherstar.auth.protocol.AuthResponseCode;
import com.furtherstar.auth.service.AuthService;
import com.furtherstar.core.context.WorkWithRoles;
import com.yummy.convention.exception.AssertUtil;
import com.yummy.convention.http.Response;
import com.yummy.security.User;
import com.yummy.web.context.RequestContext;

@RestController
@RequestMapping("/auth")
public class AuthController {
	
	@Autowired
	private AuthService authService;

	@PostMapping("/login")
	public Response<String> login(@RequestBody UserCredential userCredential){
		String sessionid = authService.login(userCredential);
		if(authService.checkUserSecretExpiry()) {
			return Response.error(AuthResponseCode.SECRET_EXPIRY, sessionid);
		}
		return Response.success(sessionid);
	}
	
	@GetMapping("/logout")
	public Response<Boolean> Logout(){
		authService.logout();
		return Response.success(true);
	}
	
	@GetMapping("/currentUser")
	public Response<User> currentUser(){
		return Response.success(RequestContext.getCurrentUser());
	}
	
	@GetMapping("/workWithRoles/list")
	public Response<List<WorkWithRoles>> getUserWorkWithRoles(){
		return Response.success(authService.getUserWorkWithRoles());
	}
	
	@GetMapping("/app/list")
	public Response<List<App>> getAuthorizedApps(){
		return Response.success(authService.getAuthorizedApps());
	}

	@GetMapping("/work/list")
	public Response<List<CorpWork>> getUserWorks(){
		return Response.success(authService.getUserWorks());
	}
	
	@PostMapping("/authorize")
	public Response<AuthorizedResources> authorize(@RequestBody AuthorizationApply apply){
		AssertUtil.notNull(apply.getAppname(),"appname不能为空");
		return Response.success(authService.authorize(apply));
	}
	
	@PostMapping("/changePassoword")
	public Response<Boolean> changePassword(@RequestBody PasswordChangeApply passwordChangeApply){
		return Response.success(authService.changePassword(passwordChangeApply));
	}
}
